package com.xwz.fullstack.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xwz.fullstack.entity.LeaveStudy;
import com.xwz.fullstack.common.Result;
import com.xwz.fullstack.mapper.LeaveStudyMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author XiaoWenzhuo
 * @since 2021-11-15
 */
@Slf4j
@RestController
@RequestMapping("/leaveStudy")
public class LeaveStudyController {
    @Resource
    LeaveStudyMapper LeaveStudyMapper;


    @PostMapping
    public Result<?> save(@RequestBody LeaveStudy leaveStudy){
        leaveStudy.setDateWeek(DateUtil.weekOfYear(DateUtil.date()));
        leaveStudy.setDateNow(DateUtil.date());
        LambdaQueryWrapper<LeaveStudy> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LeaveStudy::getNameStudent,leaveStudy.getNameStudent());
        wrapper.eq(LeaveStudy::getDateWeek,leaveStudy.getDateWeek());
        List<LeaveStudy> leaveStudies = LeaveStudyMapper.selectList(wrapper);
        leaveStudy.setLeaveNumber(String.valueOf(leaveStudies.size()+1));
        LeaveStudyMapper.insert(leaveStudy);
        log.info("研学请假新增1------》 " + leaveStudy.toString());
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody LeaveStudy leaveStudy) {
        LeaveStudyMapper.updateById(leaveStudy);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public  Result<?> deleteById(@PathVariable int id) {
        LeaveStudyMapper.deleteById(id);
        log.warn("研学请假删除------》deleteById(" + id + ")");
        return Result.success();
    }
    @GetMapping("/findAll")
    public Result<?> findAll() {
        QueryWrapper<LeaveStudy> queryWrapper = new QueryWrapper<>();

        List<LeaveStudy> list = LeaveStudyMapper.selectList(queryWrapper);
        return Result.success(list);
    }
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<LeaveStudy> wrapper = Wrappers.<LeaveStudy>lambdaQuery();
        wrapper.orderByDesc(LeaveStudy::getId);
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(LeaveStudy::getTimeDate, search);
        }
        Page<LeaveStudy> userPage = LeaveStudyMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(userPage);
    }

}

